/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.type;

/**
 *
 * @author CEABSF
 */
public class CPF {

    private String nCPF = "";
    private String DV = "";

    public CPF(String text) throws Exception{
        this.setCPF(text);
        if(!this.check())
             throw new Exception("Erro: "+text+" nao esta no formato valido de um CPF !");
    }

    private String FormatNum(String text){
        String temp = "";
        if(text.length()==11){
            temp = text;
        }else{
            if(text.length()==9){
                temp = text;
                temp += this.createDV();
            }else{
                if(text.length()==14){
                    text = text.replace(".", "");
                    text = text.replace("-", "");
                    temp = text;
                }
            }
        }
        return temp;
    }

    private boolean check(){
        if(DV.compareToIgnoreCase(this.createDV()) != 0){
            return false;
        }
       return true;
    }

    private void setCPF(String text){
        nCPF = FormatNum(text).substring(0,9);
        DV = FormatNum(text).substring(9,11);
    }

    public String getCPF(){
        return nCPF+DV;
    }
    
    @Override
    public String toString()
    {
        return nCPF.substring(0,3)+"."+nCPF.substring(3,3)+"."+nCPF.substring(6,3)+"-"+DV;
    }


    private String createDV(){
        int temp = 0,temp2 = 0;
        String DV = "";
        for(int i=0;i<=9;i++){
            if(i>0){
                temp += (Integer.parseInt(String.valueOf(nCPF.charAt(i-1))))*i;
            }
            if(i<9){
                temp2 += (Integer.parseInt(String.valueOf(nCPF.charAt(i))))*i;
            }else{
                if(temp%11 != 10){
                    temp = temp%11;
                    DV += temp;
                }else{
                    temp = 0;
                    DV = "0";
                }
                temp2 += temp*i;
                if(temp2%11 !=0){
                    DV += temp2%11;
                }else{
                    DV += "0";
                }
            }
        }
        return DV;
    }

}